package dtec.project.whereareu;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class List_user extends ListActivity implements AccelerometerListener {
	String DURL=MainActivity.URL+"/mapproject/searchuser.php";
	private SimpleCursorAdapter dataAdapter;
	private UserLocation CountriesDbAdapter;
	UserLocation db;
	JSONArray jarray;
	EditText se;
	public final Handler mHandler = new Handler();
//Button bt;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_user);
		db=new UserLocation(this);
		se=(EditText)findViewById(R.id.searchtext);
		//
		//if(accelero)		
		//
//		bt=(Button)findViewById(R.id.button1);
//		bt.setOnClickListener(new OnClickListener(){
//
//			@Override
//			public void onClick(View arg0) {
//				// TODO Auto-generated method stub
//			    Intent intent = new Intent(List_view.this, MainActivity.class);
//			    startActivity(intent);
//				
//			}});
//		String data=new String[]{};
//		ListAdapter adapter=new ArrayAdapter<String>(this,data);

//		  ListView listView = (ListView) findViewById(R.id.listView1);
//		  listView.setAdapter(dataAdapter);

	}
	public void showdata(Cursor cursor){
		  int[] to = new int[] { 
				  	R.id.t1,
				    R.id.t2,
				    R.id.t3
				  };
		  UserLocation db=new UserLocation(this);
		  dataAdapter = new SimpleCursorAdapter(
				    this, R.layout.list, 
				    cursor, 
				    new String[]{"_id","name","date"}, 
				    to,
				    0);
		  setListAdapter(dataAdapter);
	}
	public void resetshowdata(){
	    new Thread () {

	        boolean success = false;

	        public void run() {
	            try {
	                // XML-Parsing and Table-Updating code

	            } catch (Exception e) {
	                success = false;
	            }

	            mHandler.post(new Runnable() {
	                public void run() {
	                    dataAdapter.getCursor().requery(); // ECLIPSE HATES
	                }
	            });
	        }
	    }.start();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent(List_user.this, Mapdraw.class);
		Cursor c=(Cursor)dataAdapter.getItem(position);
		intent.putExtra("recid", c.getInt(c.getColumnIndex("uid")));
		startActivity(intent);
	}
	
	//network class
	private class letLogin extends AsyncTask<String ,String ,String > {

		@Override
		protected String doInBackground(String... params) {
			String urlparam = null;
			// TODO Auto-generated method stub
			try {
				urlparam=URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(params[0].toString(),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String s=sendHttpPost(urlparam,DURL);
			return s;
		}
	    protected void onPostExecute(String result) {
	    	//Login.flag=result;
	    	if(result!=null&&result!=""){
		    	try {
		    		JSONArray ja=new JSONArray(result);
		    		jarray=ja;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    	try {
		    		for(int i=0;i<jarray.length();i++){
		    			JSONObject job=jarray.getJSONObject(i);
		    			int num=job.getInt("uid");
		    			double latitude=job.getDouble("latitude"),longtitude=job.getDouble("longtitude");
		    			String name=job.getString("name"),date=job.getString("date");
		    			db.insertData(num,date,latitude, longtitude, name);
		    		}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    	showdata(db.getalldata());
	    	}
	    	else{
	            Toast.makeText(getBaseContext(), "Not found", 
        		Toast.LENGTH_LONG).show();
	    	}

	    }
	    //send data to server
	    public String sendHttpPost(String data,String u){
	    	String result=null;
	    	try {
				URL url=new URL(u);
				try {
					
					///set up
					HttpURLConnection cont=(HttpURLConnection)url.openConnection();
					cont.setRequestMethod("POST");
					cont.setConnectTimeout(6*1000);
					cont.setDoInput(true);
					cont.setDoOutput(true);
					cont.setUseCaches(false);
					
					///send
					DataOutputStream out=new DataOutputStream(cont.getOutputStream());
					out.writeBytes(data);
					out.flush();
					out.close();
					
					///get result
					InputStream in=cont.getInputStream();
					BufferedReader readin=new BufferedReader(new InputStreamReader(in,"UTF-8"));
					String line;
					StringBuffer respon=new StringBuffer();
					while((line=readin.readLine())!=null){
						respon.append(line);
						respon.append("\n");
					}
					readin.close();
					result=respon.toString();
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	return result;
	    }
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_list_user, menu);
		return true;
	}
	@Override
	public void onAccelerationChanged(float x, float y, float z) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onShake(float force) {
		// TODO Auto-generated method stub
		db.resetData();
		if(se.getText().toString()!=null&&se.getText().toString()!=""){
			new letLogin().execute(se.getText().toString());
		}
		else{
			resetshowdata();
		}
//		Toast.makeText(getBaseContext(), "shake", 
//        		Toast.LENGTH_LONG).show();
	}

	@Override
    public void onResume() {
            super.onResume();
//            Toast.makeText(getBaseContext(), "onResume Accelerometer Started", 
//            		Toast.LENGTH_LONG).show();
            
            if (AccelerometerManager.isSupported(this)) {
            	
    			AccelerometerManager.startListening(this);
            }
    }
	@Override
    public void onStop() {
            super.onStop();
            
            if (AccelerometerManager.isListening()) {
            	
    			AccelerometerManager.stopListening();
    			
//    			Toast.makeText(getBaseContext(), "onStop Accelerometer Stoped", 
//    					Toast.LENGTH_LONG).show();
            }
           
    }
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i("Sensor", "Service  distroy");
		
		if (AccelerometerManager.isListening()) {
			
			AccelerometerManager.stopListening();
			
//			Toast.makeText(getBaseContext(), "onDestroy Accelerometer Stoped", 
//					Toast.LENGTH_LONG).show();
        }
			
	}
}
